import 'package:get_storage/get_storage.dart';
import '../model/user_model.dart';

class UserStorageService {
  static final UserStorageService _instance = UserStorageService._internal();
  factory UserStorageService() => _instance;
  UserStorageService._internal();

  final GetStorage _storage = GetStorage();

  static const String _userKey = 'user_info';
  static const String _isLoggedInKey = 'is_logged_in';
  static const String _googleBindingKey = 'google_binding_status';

  /// 保存用户信息
  Future<void> saveUser(UserModel user) async {
    await _storage.write(_userKey, user.toJson());
    await _storage.write(_isLoggedInKey, true);
  }

  /// 保存苹果授权信息
  Future<void> saveAppleToken(String token) async {
    await _storage.write("apple_token", token);
  }

  Future<void> saveAppleId(String appleId) async {
    await _storage.write("apple_id", appleId);
  }

  ///获取苹果授权信息
  String? getAppleToken() {
    return _storage.read("apple_token");
  }
  String? getAppleId() {
    return _storage.read("apple_id");
  }


  /// 获取用户信息
  UserModel? getUser() {
    final userData = _storage.read(_userKey);
    if (userData != null) {
      return UserModel.fromJson(Map<String, dynamic>.from(userData));
    }
    return null;
  }

  /// 更新用户信息
  Future<void> updateUser(UserModel user) async {
    await _storage.write(_userKey, user.toJson());
  }

  /// 获取访问Token
  String? getAccessToken() {
    final user = getUser();
    print('accessToken ===: ${user?.accessToken}');
    return user?.accessToken;
  }

  /// 获取用户ID
  String? getUserId() {
    final user = getUser();
    return user?.uid.toString();
  }

  /// 获取用户名
  String? getUsername() {
    final user = getUser();
    return user?.nickname;
  }

  /// 检查是否登录
  bool isLoggedIn() {
    final isLoggedIn = _storage.read(_isLoggedInKey) ?? false;
    final user = getUser();

    // 检查登录状态和Token有效性
    if (!isLoggedIn || user == null || !user.hasValidToken) {
      return false;
    }

    return true;
  }

  /// 检查是否为新用户
  bool isNewUser() {
    final user = getUser();
    return user?.isNewUser ?? false;
  }

  /// 设置谷歌绑定状态
  Future<void> setGoogleBindingStatus(bool isBound) async {
    await _storage.write(_googleBindingKey, isBound);
  }

  /// 获取谷歌绑定状态
  bool getGoogleBindingStatus() {
    return _storage.read(_googleBindingKey) ?? false;
  }

  /// 清除用户数据
  Future<void> clearUserData() async {
    await _storage.remove(_userKey);
    await _storage.write(_isLoggedInKey, false);
    await _storage.remove(_googleBindingKey);
  }

  /// 清除所有数据
  Future<void> clearAll() async {
    await _storage.erase();
  }
}
